package com.server.http.anYuan;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.server.pojo.MobileApp;
import com.server.pojo.Unit;
import com.server.libs.ret.RE;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class AnYuanServer {
    private static final String REQUEST_URL = "http://121.31.111.154:8337/";
    private static final HttpHeaders REQUEST_HEADERS = new HttpHeaders();

    static {
        REQUEST_HEADERS.setContentType(MediaType.APPLICATION_JSON);
    }

    public static JSONObject tryRequest(Map<String, Object> data) {
        return request(data);
    }

    public static JSONObject request(Map<String, Object> data) throws RE {
        data.put("serverid", 1);

//        log.info("AnYuan请求数据：" + JSONObject.toJSONString(data));
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> requestEntity = new HttpEntity<>(JSONObject.toJSONString(data), REQUEST_HEADERS);
        ResponseEntity<String> response = restTemplate.exchange(REQUEST_URL, HttpMethod.POST, requestEntity, String.class);
        String body = response.getBody();
        if (body == null || body.trim().isEmpty()) return null;
//        log.info("AnYuan返回数据：" + body);
        JSONObject res = JSON.parseObject(body);
        if (res.getInteger("return") != 0) {
            throw new RE(res.getString("message"));
        }

        return res;
    }

    public static JSONObject register(MobileApp mobileApp) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("com", 102);
        requestBody.put("admin", mobileApp.getAccount());
        requestBody.put("pass", mobileApp.getPassword());
        requestBody.put("name", mobileApp.getName());
        requestBody.put("sex", mobileApp.getSex());
        requestBody.put("jobcode", mobileApp.getJob());
        requestBody.put("act", "1");
        return request(requestBody);
    }

    public static JSONObject passUpdate(MobileApp mobileApp,String oldPassword) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("com", 114);
        requestBody.put("admin", mobileApp.getAccount());
        requestBody.put("pass", oldPassword);
        requestBody.put("newpass", mobileApp.getPassword());
        return request(requestBody);
    }
    public static JSONObject renew(MobileApp mobileApp) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("com", 102);
        requestBody.put("admin", mobileApp.getAccount());
        requestBody.put("pass", mobileApp.getPassword());
        requestBody.put("name", mobileApp.getName());
        requestBody.put("sex", mobileApp.getSex());
        requestBody.put("tel", mobileApp.getTel());
        requestBody.put("jobcode", mobileApp.getJob());
        requestBody.put("act", "2");
        return request(requestBody);
    }

    public static JSONObject login(MobileApp mobileApp) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("com", 110);
        requestBody.put("admin", mobileApp.getAccount());
        requestBody.put("pass", mobileApp.getPassword());
        requestBody.put("act", "0");
        return request(requestBody);
    }

    public static JSONObject destroy(MobileApp mobileApp) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("com", 102);
        requestBody.put("admin", mobileApp.getAccount());
        requestBody.put("pass", mobileApp.getPassword());
        requestBody.put("act", "0");
        return request(requestBody);
    }

    public static JSONObject bindUnit(MobileApp mobileApp, Unit unit) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("com", 103);
        requestBody.put("admin", mobileApp.getAccount());
        requestBody.put("uid", unit.getCode());
        requestBody.put("act", "1");
        return request(requestBody);
    }

    public static JSONObject unBindUnit(MobileApp mobileApp, Unit unit) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("com", 103);
        requestBody.put("admin", mobileApp.getAccount());
        requestBody.put("uid", unit.getCode());
        requestBody.put("act", "0");
        return request(requestBody);
    }

    public static JSONObject position(MobileApp mobileApp) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("com", 202);
        requestBody.put("admin", mobileApp.getAccount());
        requestBody.put("jingdu", mobileApp.getLongitude());
        requestBody.put("weidu", mobileApp.getLatitude());
        return request(requestBody);
    }

    public static List<Unit> getUnit() {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("com", 115);
        requestBody.put("ucode", 0);
        requestBody.put("admin", "18076605596");
        requestBody.put("pass", "1");
        JSONObject request = request(requestBody);
        JSONArray array = JSONArray.from(request.get("data"));
        List<Unit> units = new ArrayList<>();

        for (Object o : array) {
            JSONObject var = JSONObject.from(o);
            Unit unit = new Unit();
            unit.setCode(var.getString("uid"));
            unit.setName(var.getString("urname"));
            unit.setAddr(var.getString("uaddr"));
            units.add(unit);
        }

        return units;
    }




    public static void sendLocations(List<MobileApp> mobileApps) {
        Map<String, Object> data = new HashMap<>();
        data.put("com", 203);
        data.put("appnum", mobileApps.size());
        List<Object> appdata = new ArrayList<>();
        for (MobileApp mobileApp : mobileApps) {
            if (!mobileApp.isHaveLocation()) continue;
            Map<String, Object> app = new HashMap<>();
            app.put("admin", mobileApp.getAccount());
            app.put("jingdu", mobileApp.getLongitude());
            app.put("weidu", mobileApp.getLatitude());
            appdata.add(app);
        }
        data.put("appdata", appdata);
        AnYuanServer.request(data);
    }

    public static void sendOlineApp(List<MobileApp> mobileApps, int delay) {
        CompletableFuture.runAsync(() -> {
            int batchSize = 10000; // 每组的大小
            if (mobileApps.isEmpty()){
                Map<String, Object> data = new HashMap<>();
                data.put("com", 118);
                data.put("appnum", 0);
                data.put("appdata", new ArrayList<>());
                AnYuanServer.request(data);
            }
            for (int i = 0; i < mobileApps.size(); i += batchSize) {
                int endIndex = Math.min(i + batchSize, mobileApps.size());
                List<MobileApp> batch = mobileApps.subList(i, endIndex);

                Map<String, Object> data = new HashMap<>();

                data.put("com", 118);
                data.put("appnum", batch.size());
                List<Map<String, Object>> appdata = new ArrayList<>();
                for (MobileApp mobileApp : batch) {

                    HashMap<String, Object> var = new HashMap<>();
                    var.put("admin", mobileApp.getAccount());
                    var.put("loginip", mobileApp.getIp());
                    var.put("loginport", mobileApp.getPort());
                    appdata.add(var);
                }
                data.put("appdata", appdata);

                AnYuanServer.request(data);
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

//    public static void main(String[] args) {
//        System.out.println(getUnit());
//    }

}
